<?php
/**
 * 数字货币自动化生成类
 * Created by PhpStorm.
 * User: jason
 * Date: 18-10-11
 * Time: 上午9:36
 */
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Cookie;
use Illuminate\Support\Facades\DB;
use think\Cache;
use think\Config;
use View;
class AutoController extends Controller
{
    //币智慧api地址
    private $api = 'api.bizhihui.info';
    //token
    public $TOKEN = '2399c18e8641436b7b3f3e12a71733e1';
    public $api_method = '';
    public $req_method = '';

    //自动话功能说明
    public function index(){
        return view('auto.index');
    }

    //获取全球火币网币种列表
    public function getHuobiList(){
        //设置脚本时间
        set_time_limit(100);
        //获取火币网所有币种api
        $url = 'https://api.huobipro.com/v1/common/symbols';
        $rs_coins = $this->curl_request($url);
        $rs_coins = json_decode($rs_coins,true);
        //判断状态
        if ($rs_coins['status'] == 'ok') {
            $coins = $rs_coins['data'];
            $insert_coins = [];     //添加币种
            $insert_details =[];    //添加类型
            foreach ($coins as $coin) {
                //判断该币种是否添加
                $where = [
                    'name'              => strtoupper($coin['base-currency']),//币种名称
                    'exchange_id'       => 1,//火币全球站
                    'base_currency'     => $coin['base-currency'],//基础币种
                    'quote_currency'    => $coin['quote-currency'],//计价币种
                    'symbol'            => $coin['symbol'],//简称
                ];
                $is_insert = DB::table('coin')->where($where)->value('coin_id');
                //没有该币种则添加
                if (!$is_insert) {
                    $data = $where;
                    $data['addtime'] = time();
                    $rs = DB::table('coin')->insert($data);
                    if ($rs) {
                        $insert_coins[] = $data['name'];
                        echo '添加币成功 :'.json_encode($data).'<hr>';
                    }
                } else {
                    echo '添加币失败（已添加） :'.json_encode($where).'<hr>';
                }
            }
            //统计添加币种数量
            $count_coin = count($insert_coins);
            //币种类型添加
            $insert_coins = array_unique($insert_coins);    //添加币种去重
            foreach ($insert_coins as $name) {
                //判断该币类型是否拥有
                $where = [
                    'name' => $name
                ];
                $is_insert = DB::table('coin_details')->where($where)->value('coin_details_id');
                //没有该币种则添加
                if (!$is_insert) {
                    $data = $where;
                    $rs = DB::table('coin_details')->insert($data);
                    if ($rs) {
                        $insert_details[] = $data;
                        echo '添加币类型成功:'.json_encode($data).'<br/>';
                        flush();
                    }
                } else {
                    echo '添加币类型失败（已添加） :'.json_encode($where).'<hr>';
                }
            }
            //统计添加类型数量
            $count_detail = count($insert_details);
            //统计添加类型数量
            echo '添加币种:'.$count_coin.'个,添加类型：'.$count_detail;
        }
    }

    //币安获取所有币种列表
    public function getBianList(){
        //币安数据地址
        $url = 'https://api.binance.com/api/v1/exchangeInfo';
        $rs_coins = $this->curl_request($url);
        $rs_coins = json_decode($rs_coins,true);
        if (isset($rs_coins['symbols']) && !empty($rs_coins['symbols'])) {
            $coins = $rs_coins['symbols'];
            $insert_coins = [];     //添加币种
            $insert_details =[];    //添加类型
            foreach ($coins as $coin) {
                //判断该币种是否添加
                $where = [
                    'name'              => $coin['baseAsset'],//币种名称
                    'exchange_id'       => 2,//币安网
                    'base_currency'     => strtolower($coin['baseAsset']),//基础币种
                    'quote_currency'    => strtolower($coin['quoteAsset']),//计价币种
                    'symbol'            => strtolower($coin['symbol']),//简称
                ];
                $is_insert = DB::table('coin')->where($where)->value('coin_id');
                //没有该币种则添加
                if (!$is_insert) {
                    $data = $where;
                    $data['addtime'] = time();
                    $rs = DB::table('coin')->insert($data);
                    if ($rs) {
                        $insert_coins[] = $data['name'];
                        echo '添加币成功 :'.json_encode($data).'<hr>';
                    }
                } else {
                    echo '添加币失败（已添加） :'.json_encode($where).'<hr>';
                }
            }
            //统计添加币种数量
            $count_coin = count($insert_coins);
            //币种类型添加
            $insert_coins = array_unique($insert_coins);    //添加币种去重
            foreach ($insert_coins as $name) {
                //判断该币类型是否拥有
                $where = [
                    'name' => $name
                ];
                $is_insert = DB::table('coin_details')->where($where)->value('coin_details_id');
                //没有该币种则添加
                if (!$is_insert) {
                    $data = $where;
                    $rs = DB::table('coin_details')->insert($data);
                    if ($rs) {
                        $insert_details[] = $data;
                        echo '添加币类型成功:'.json_encode($data).'<br/>';
                        flush();
                    }
                } else {
                    echo '添加币类型失败（已添加） :'.json_encode($where).'<hr>';
                }
            }
            //统计添加类型数量
            $count_detail = count($insert_details);
            //统计添加类型数量
            echo '添加币种:'.$count_coin.'个,添加类型：'.$count_detail;
        }
    }

    //获取币种全称，方便菲小号抓取数据
    public function getCoinDetail(){
        //设置脚本时间
        set_time_limit(0);
        //获取所有币种
        $coins = DB::table('coin_details')->get();
        $coins = $this->objectToArr($coins);
        $update_num = 0;    //修改数据条数
        foreach ($coins as $coin) {
            $data = [];
            //获取币基本信息
            $coin_quotation = $this->get_coin_quotation($coin['name']);
            $coin_quotation = json_decode($coin_quotation, true);
            if ($coin_quotation['code'] == 200) {
                $coin_quotation = $coin_quotation['data'];
                //名字为空才修改
                if (empty($coin['c_name'])) {
                    $data['c_name'] = isset($coin_quotation['cn']) ? $coin_quotation['cn'] : '';
                }
                //全称为空才修改
                if (empty($coin['full_name'])) {
                    $data['full_name'] = isset($coin_quotation['name']) ? $coin_quotation['name'] : '';
                }
            }
            $coin_base = $this->get_coin_basic($coin['name']);
            $coin_base = json_decode($coin_base,true);
            if ($coin_base['code'] == 200) {
                $coin_base = $coin_base['data'];
                //简介为空才修改
                /*if (empty($coin['descriptions'])) {
                    $data['descriptions'] = isset($coin_base['descriptions']['zh'][0]) ? $coin_base['descriptions']['zh'][0] :
                        '';
                }*/
                //获取发行时间，毫秒时间戳，所以除以1000
                //发行时间为空才修改
                if (empty($coin['publish_time'])) {
                    $data['publish_time'] = isset($coin_base['publish_time']) ? ceil($coin_base['publish_time'] / 1000) : 0;
                }
            }
            //有数据修改才执行
            if (!empty($data)) {
                $rs = DB::table('coin_details')->where('coin_details_id', $coin['coin_details_id'])->update($data);
                if ($rs) {
                    echo $coin['name'] . '详情修改:' . json_encode($data) . '<hr>';
                    print str_pad("", 10000);
                    flush();
                    $update_num ++ ;
                }
            }
        }
        echo '修改详情个数:'.$update_num.'<hr>';
    }

    //菲小号抓取币详情数据
    public function getFeiXH(){
        //从菲小号抓取数据
        $coins = DB::table('coin_details')->get();
        $coins = $this->objectToArr($coins);
        foreach ($coins as $coin) {
            $data = [];
            $coin_name = strtolower($coin['full_name']);
            $coin_name = str_replace(' ','-',$coin_name);
            if ($coin_name == '' || !empty($coin['descriptions'])){
                continue;
            }
            //去菲小号币种介绍获取详情介绍
            $url = 'https://www.feixiaohao.com/coindetails/'.$coin_name;
            @$text = file_get_contents($url);
            $text = str_replace("<br>", '', $text);
            preg_match("/<p.*>(.*)<\/div>/isU", $text, $match);
            if (isset($match[1]) && !empty($match[1])) {
                $descriptions = $match[1];
                $descriptions = str_replace('<p>','',$descriptions);
                //如果没有介绍才修改
                if (empty($coin['descriptions'])) {
                    $data['descriptions'] = $descriptions;
                    $rs = DB::table('coin_details')->where('coin_details_id',$coin['coin_details_id'])->update($data);
                    if ($rs) {
                        echo $coin['name'].'详情修改:'.json_encode($data).'<hr>';
                        print str_pad("", 10000);
                        flush();
                    }
                }
            }
        }
    }


    //抓取币种流通量及流通总量
    public function getCoinSupply(){
        $coins = DB::table('coin_details')->get();
        $coins = $this->objectToArr($coins);
        foreach ($coins as $coin) {
            $data = [];
            $coin_name = strtolower($coin['full_name']);
            $coin_name = str_replace(' ', '-', $coin_name);
            if ($coin_name == '') {
                continue;
            }
            //去菲小号抓取发行量和发行总量
            $url = 'https://www.feixiaohao.com/currencies/'.$coin_name;
            @$text = file_get_contents($url);
            preg_match("/流通量<\/div><div class=value>(.*)<\/div>/isU", $text, $total_supply);
            preg_match("/总发行量<\/div><div class=value>(.*)<\/div>/isU", $text, $max_supply);
            preg_match("/发行时间：<\/span> <span class=value>(.*)<\/span>/isU",$text,$publish_time);
            if (isset($total_supply[1]) && !empty($total_supply[1]) && isset($max_supply[1]) && !empty
                ($max_supply[1])) {
                //格式处理
                $total_supply = $total_supply[1];
                $max_supply = $max_supply[1];
                $total_supply = preg_replace("/[A-Z]||\,|| /","",$total_supply);
                $max_supply = preg_replace("/[A-Z]||\,|| /","",$max_supply);
                //如果没数据设置成０
                $total_supply = $total_supply == '?' ? 0 : $total_supply;
                $max_supply = $max_supply == '?' ? 0 : $max_supply;
                //修改数据
                $data = [
                    'total_supply' => $total_supply,    //总发行量
                    'max_supply'  => $max_supply,       //流通量
                ];
                //是否获发行时间
                if (isset($publish_time[1]) && !empty($publish_time[1]) && empty($coin['publish_time'])) {
                    $data['publish_time'] = strtotime($publish_time[1]);
                }
                $rs = DB::table('coin_details')->where('coin_details_id',$coin['coin_details_id'])->update($data);
                if ($rs) {
                    echo $coin['name'].'数据修改:'.json_encode($data).'<hr>';
                    print str_pad("", 10000);
                    flush();
                }
            }
        }
    }

    /**
     * 获取币种基本信息
     * @param key 	string 	查询币的名称或中文名或英文名,获取币种列表接口中的_id就是参数 	必选
     * @return mixed
     */
    public function get_coin_basic($key = '')
    {
        $this->api_method = "/v1/coin_basic";
        $this->req_method = 'GET';
        $param = [
            'key' => $key
        ];
        $url = $this->create_sign_url($param);
        return $this->curl_request($url);
    }

    /**
     * 获取币种行情
     * @param key 	string 	查询币的名称或中文名或英文名,参数使用币种列表接口中的_id 	必选
     * @return mixed
     */
    public function get_coin_quotation($key= '')
    {
        $this->api_method = "/v1/coin_quotation";
        $this->req_method = 'GET';
        $param = [
            'key' => $key
        ];
        $url = $this->create_sign_url($param);
        return $this->curl_request($url);
    }

    //币智慧生成验签URL
    public function create_sign_url($append_param = [])
    {
        // 验签参数
        $param = [
            'token' => $this->TOKEN
        ];
        if ($append_param) {
            foreach ($append_param as $k => $ap) {
                $param[$k] = $ap;
            }
        }
        return 'http://' . $this->api . $this->api_method . '?' . $this->bind_param($param);
    }

    //组合参数
    public function bind_param($param)
    {
        $u = [];
        $sort_rank = [];
        foreach ($param as $k => $v) {
            $u[] = $k . "=" . urlencode($v);
            $sort_rank[] = ord($k);
        }
        asort($u);
        return implode('&', $u);
    }
}